import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
	providedIn: 'root',
})
export class PermissionService {
	constructor(private http: HttpClient) {}
	async submit(zoneID: number, config: PermissionConfig) {
		const data = await PermissionConfigToFormData(config);
		await this.http.post(`/api/admin/area/${zoneID}/auth`, data).toPromise();
	}
}

async function PermissionConfigToFormData(value: PermissionConfig) {
	const formData = new FormData();
	// user
	{
		formData.set('select_all_user', BoolFormat(value.user.all));
		if (!value.user.all) {
			value.user.selected.forEach(u => formData.append('user_ids', u.id));
		}
	}
	// pc
	{
		formData.set('select_all_pc', BoolFormat(value.pc.all));
		formData.set('pc_auth', BoolFormat(value.pc.auth));
		if (!value.pc.all) {
			value.pc.selected.forEach(pc => formData.append('pc_ids', pc.id));
		}
	}
	// software
	{
		formData.set('select_all_software', BoolFormat(value.software.all));
		formData.set('software_auth', BoolFormat(value.software.auth));
		if (!value.software.all) {
			value.software.selected.forEach(soft => formData.append('software_ids', soft.id));
		}
	}
	// config
	{
		formData.set('pc_config', JSON.stringify(value.pc_config));
		const wallpaper = await BlobFile(value.pc_config.wallpaper.image);
		if (wallpaper) {
			formData.set('wallpaper', wallpaper);
		}
		const script = await BlobFile(value.pc_config.script.content);
		if (script) {
			formData.set('script', script);
		}
	}
	formData.set('exec', BoolFormat(false));
	return formData;
}

function BoolFormat(b: boolean) {
	return Number(b).toString();
}

async function BlobFile(v: string) {
	if (!v.startsWith('blob:http')) {
		return null;
	}
	const resp = await fetch(v);
	return resp.blob();
}

export interface PermissionConfig {
	id: number;
	user: SelectResource;
	pc: SelectResource;
	software: SelectResource;
	pc_config: Pcconfig;
}

interface Pcconfig {
	iptables: Iptables;
	screensaver: Screensaver;
	power: Power;
	pam_cracklib: Pamcracklib;
	wallpaper: Wallpaper;
	script: Script;
}

interface Script {
	name: string;
	content: string;
}

interface Wallpaper {
	image: string;
}

interface Pamcracklib {
	minlen: number;
	reject_username: boolean;
	minclass: number;
}

interface Power {
	display_standby: number;
}

interface Screensaver {
	enable: boolean;
	delay: number;
}

interface Iptables {
	content: string;
}

interface SelectResource {
	all: boolean;
	selected: any[];
	auth: boolean;
}
